package spark.graphics;

import com.sun.opengl.util.GLUT;

import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.glu.GLU;

public class Renderer {
	private static Renderer instance = new Renderer();

	private GLAutoDrawable renderingArea = null;
	private GLU glu = new GLU();
	private GL gl = null;

	private Renderer() {
	}

	public void initialize(GLAutoDrawable renderingArea) {
		this.renderingArea = renderingArea;
		gl = renderingArea.getGL();
		initializeOpenGL();
	}

	public void swapBuffers() {

	}

	public void resizeScenePerspectiveFov() {
		int width = renderingArea.getWidth();
		int height = renderingArea.getHeight();
		gl.glViewport(0, 0, width, height);
		float aspectRatio = (float) width / (float) height;
		Camera.setProjectionPerspectiveFov(gl, glu, 45.0f, aspectRatio, 0.1f, 1000.0f);

		gl.glEnable(GL.GL_CULL_FACE);
		gl.glCullFace(GL.GL_BACK);
	}

	public void resizeSceneOrtho() {
		resizeSceneOrtho(0, 0, renderingArea.getWidth(), renderingArea.getHeight());
	}

	public void resizeSceneOrtho(int x, int y, int width, int height) {
		Camera.setProjectionOrtho(gl, glu, x, y, width, height);

		gl.glEnable(GL.GL_CULL_FACE);
		gl.glCullFace(GL.GL_BACK);
	}

	public void setVSync(boolean aEnabled) {
		if(aEnabled)
			gl.setSwapInterval(1);
		else
			gl.setSwapInterval(0);
	}

	private void initializeOpenGL() {
		gl.glShadeModel(GL.GL_SMOOTH);							// Enable Smooth Shading
		gl.glClearColor(100.0f / 255.0f, 149.0f / 255.0f, 237.0f / 255.0f, 0.0f);				// blueish Background
		gl.glClearDepth(1.0f);									// Depth Buffer Setup
		gl.glEnable(GL.GL_DEPTH_TEST);							// Enables Depth Testing
		gl.glDepthFunc(GL.GL_LEQUAL);								// The Type Of Depth Testing To Do
		gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);	// Really Nice Perspective Calculations
	}

	public static Renderer getInstance() {
		return instance;
	}

	public GLU getGlu() {
		return glu;
	}

	public GL getGl() {
		return gl;
	}

	public int getRenderAreaWidth() {
		return renderingArea.getWidth();
	}

	public int getRenderAreaHeight() {
		return renderingArea.getHeight();
	}
}
